package cn.sccl.dirms.topo.discovery.service.impl;

import cn.sccl.common.dao.BaseDAO;
import cn.sccl.common.model.PageResult;
import cn.sccl.common.model.QueryData;
import cn.sccl.common.scheduler.model.TaskFireLog;
import cn.sccl.common.service.impl.BaseManagerImpl;
import cn.sccl.dirms.topo.discovery.dao.DiscoverTaskDAO;
import cn.sccl.dirms.topo.discovery.model.DiscoverRule;
import cn.sccl.dirms.topo.discovery.model.DiscoverTask;
import cn.sccl.dirms.topo.discovery.model.DiscoverTaskVO;
import cn.sccl.dirms.topo.discovery.service.DiscoverTaskManager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* 自动发现任务表 的Manager实现类
* Created by _minus on 2017-09-26.
*/
@Service
public class DiscoverTaskManagerImpl extends BaseManagerImpl<DiscoverTask> implements DiscoverTaskManager{

    @Autowired
    private DiscoverTaskDAO discoverTaskDAO;

    public DiscoverTaskDAO getDiscoverTaskDAO(){
        return discoverTaskDAO;
    }

    @Override
    public BaseDAO<DiscoverTask> getBaseDAO(){
        return getDiscoverTaskDAO();
    }

    /**
     * 发现待执行发现任务
     *
     * @return
     */
    @Override
    public List<DiscoverTask> getWaitTasks(){
        String sql = "select * from T_TOPO_DISCOVER_TASK where active ='10'";
        return getDataBase().query4Model(sql,DiscoverTask.class,new Object[]{});
    }


    @Override
    public List<DiscoverTask> queryDiscoverTasksByGraphyId(String id) {
        String sql = "select t.* from T_TOPO_DISCOVER_TASK t where t.graphy_id = ? and t.delete_flag= 0 order by t.create_time desc" ;
        List params = new ArrayList();
        params.add(id);
        return getDataBase().query4Model(sql,DiscoverTask.class,params.toArray());
    }

    @Override
    public PageResult<DiscoverTask> pageQueryDiscoverTasksByGraphyId(String id, long pageIndex, int pageSize, QueryData queryData) {
        String sql = "select t.* from T_TOPO_DISCOVER_TASK t where t.graphy_id = ? and t.delete_flag= 0 order by t.create_time desc" ;
        List params = new ArrayList();
        params.add(id);
        return getDataBase().query4Model(sql,pageIndex,pageSize,DiscoverTask.class,params.toArray());
    }

    @Override
    public void updateDiscoverRuleDetail(String taskId) {
        //根据taskid 获取到该task 的发现规则
        StringBuffer rsql = new StringBuffer();
        rsql.append(
                "SELECT R.*\n" +
                        "  FROM T_TOPO_DISCOVER_RULE R, T_TOPO_DISCOVER_RE_TASK_RULE RT\n" +
                        " WHERE R.DELETE_FLAG = 0\n" +
                        "   AND RT.DELETE_FLAG = 0\n" +
                        "   AND RT.DISCOVER_RULE_ID = R.ID\n" +
                        "   AND RT.TASK_ID = ?"
        );

        List params = new ArrayList();
        params.add(taskId);

        List<DiscoverRule> rules = getDataBase().query4Model(rsql.toString(),DiscoverRule.class,params.toArray());

        if (rules != null && rules.size() >0 ) {
            DiscoverTask task = get(taskId) ;
            String snapShot = getDiscoverRuleSnapShot(rules,task) ;
            task.setDiscoverRuleDetail(snapShot);
            save(task);
        }
    }


    @Override
    public List<DiscoverTaskVO> queryDiscoverTaskVoByGraphyId(String id) {

        String sql =
                "SELECT T.ID                   AS TASK_ID,\n" +
                        "       T.NAME,\n" +
                        "       T.GROUP_NAME,\n" +
                        "       T.DISCOVER_RULE_DETAIL,\n" +
                        "       T.GRAPHY_ID,\n" +
                        "       T.USER_ID,\n" +
                        "       T.ACTIVE,\n" +
                        "       T.TARGET_OBJECT,\n" +
                        "       T.TARGET_METHOD,\n" +
                        "       TS.ID                  AS TASK_SCHEDULE_ID,\n" +
                        "       TS.TYPE,\n" +
//                        "       TS.IS_REPEAT,\n" +
//                        "       TS.EVERY_DAY,\n" +
//                        "       TS.WEEKLY,\n" +
//                        "       TS.MONTHLY,\n" +
//                        "       TS.S_TIME_INTERVAL,\n" +
//                        "       TS.M_TIME_INTERVAL,\n" +
                        "       TS.START_TIME,\n" +
                        "       TS.END_TIME,\n" +
                        "       TS.CRON\n" +
                        "  FROM T_TOPO_DISCOVER_TASK T\n" +
                        "  LEFT OUTER JOIN T_TOPO_DISCOVER_SCHEDULE TS\n" +
                        "    ON T.ID = TS.TASK_ID\n" +
                        " WHERE T.GRAPHY_ID = ?\n" +
                        "   AND T.DELETE_FLAG = 0\n" +
                        "   AND TS.DELETE_FLAG = 0\n" +
                        "\n" +
                        " ORDER BY T.CREATE_TIME DESC";

        List params = new ArrayList();
        params.add(id);

        return getDataBase().query4Model(sql,DiscoverTaskVO.class,params.toArray());

    }


    @Override
    public DiscoverTaskVO queryDiscoverTaskVoByTaskId(String id) {
        String sql =
                "SELECT T.ID                   AS TASK_ID,\n" +
                        "       T.NAME,\n" +
                        "       T.GROUP_NAME,\n" +
                        "       T.DISCOVER_RULE_DETAIL,\n" +
                        "       T.GRAPHY_ID,\n" +
                        "       T.USER_ID,\n" +
                        "       T.ACTIVE,\n" +
                        "       T.TARGET_OBJECT,\n" +
                        "       T.TARGET_METHOD,\n" +
                        "       TS.ID                  AS TASK_SCHEDULE_ID,\n" +
                        "       TS.TYPE,\n" +
//                        "       TS.IS_REPEAT,\n" +
//                        "       TS.EVERY_DAY,\n" +
//                        "       TS.WEEKLY,\n" +
//                        "       TS.MONTHLY,\n" +
//                        "       TS.S_TIME_INTERVAL,\n" +
//                        "       TS.M_TIME_INTERVAL,\n" +
                        "       TS.START_TIME,\n" +
                        "       TS.END_TIME,\n" +
                        "       TS.CRON\n" +
                        "  FROM T_TOPO_DISCOVER_TASK T\n" +
                        "  LEFT OUTER JOIN T_TOPO_DISCOVER_SCHEDULE TS\n" +
                        "    ON T.ID = TS.TASK_ID\n" +
                        " WHERE T.ID = ?\n" +
                        "   AND T.DELETE_FLAG = 0\n" +
                        "   AND TS.DELETE_FLAG = 0\n" ;

        List params = new ArrayList();
        params.add(id);
        List<DiscoverTaskVO> discoverTaskVOs = getDataBase().query4Model(sql,DiscoverTaskVO.class,params.toArray());
        DiscoverTaskVO result= new DiscoverTaskVO();

        if (discoverTaskVOs != null && !discoverTaskVOs.isEmpty()) {
            result = discoverTaskVOs.get(0);
        }
        return result;

    }

    @Override
    public PageResult<TaskFireLog> pageQueryTaskFireLogsByTaskId(String taskId, long pageIndex, int pageSize, QueryData queryData) {
        StringBuffer sb = new StringBuffer();
        sb.append(
                "SELECT TL.*\n" +
                        "  FROM T_TASK_FIRE_LOG TL, T_TOPO_DISCOVER_TASK T\n" +
                        " WHERE T.DELETE_FLAG = 0\n" +
                        "   AND TL.DELETE_FLAG = 0\n" +
                        "   AND TL.TASK_NAME = T.NAME\n" +
                        "   AND TL.GROUP_NAME = T.GROUP_NAME\n" +
                        "   AND T.ID = ?\n"
        );

        List params = new ArrayList();
        params.add(taskId);
        sb.append(" ORDER BY TL.CREATE_TIME DESC") ;

        return getDataBase().query4Model(sb.toString(),pageIndex,pageSize,TaskFireLog.class,params.toArray());
    }

    private String getDiscoverRuleSnapShot(List<DiscoverRule> rules , DiscoverTask task) {
        JSONObject snapShot = new JSONObject();
        JSONObject nameJson = new JSONObject();
        JSONArray ipList = new JSONArray();
        JSONArray snmpConfig = new JSONArray();

        if (rules != null && !rules.isEmpty()) {
            nameJson.put("name",task.getName()) ;

            snapShot.put("mapInfo",nameJson) ;

            for (DiscoverRule rule : rules) {
                JSONObject ip = new JSONObject();
                JSONObject snmp = new JSONObject();
                ip.put("startIp",rule.getStartIp());
                ip.put("endIp",rule.getEndIp());
                snmp.put("community",rule.getSnmpCommunity()) ;
                snmp.put("version",rule.getSnmpVersion()) ;

                ipList.add(ip);
                snmpConfig.add(snmp);
            }

            snapShot.put("ipList",ipList);
            snapShot.put("snmpConfig",snmpConfig);

        }

        return snapShot.toString() ;
    }
}